﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Security.Permissions;
using Light.Framework.Model;
using Light.Framework.Contract;
using Light.Utility;

namespace Light.Framework.Component
{
    /// <summary>
    /// 组件基类（包含通用的CRUD方法）
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseComponent<T> where T : class, IEntity, new()
    {
        #region 基本的CRUD方法

        public virtual int Count(SearchArgs args)
        {
            return EntityMediator<T>.Count(args);
        }

        public virtual int Count(string tableOrViewName, SearchArgs args)
        {
            return DataTableMediator.Count(tableOrViewName, args);
        }

        public virtual int Count()
        {
            return Count(null);
        }

        public virtual decimal Sum(string columnName, SearchArgs args)
        {
            return EntityMediator<T>.Sum(columnName, args);
        }

        public virtual decimal Sum(string tableOrViewName, string columnName, SearchArgs args)
        {
            return DataTableMediator.Sum(tableOrViewName, columnName, args);
        }

        public virtual bool Exist(SearchArgs args)
        {
            return Count(args) > 0;
        }

        /// <summary>
        /// 新增时，为ID赋值
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [Light.Aop.CacheMethod(UpdateCache = true)]
        public virtual OperateResult Create(T obj)
        {
            OperateResult result = Validate(obj);

            if (result.IsSucced)
            {
                //强制设置ID为空GUID，确保IsNew判断无误
                //obj.ID = Guid.Empty.ToString();

                SearchArgs args = GetExistArgs(obj);
                int countExits = 0;
                if (args != null)
                {
                    countExits = EntityMediator<T>.Count(args);
                }
                if (countExits > 0)
                {
                    result.IsSucced = false;
                    result.Message = GetExistMessage(obj);
                    return result;
                }
                if (String.IsNullOrWhiteSpace(obj.ID))
                {
                    //如未设置ID，则取默认
                    obj.ID = Guid.NewGuid().ToString("N");
                }
                result = Excute(EntityMediator<T>.Create, obj, OperateType.Create);
            }
            return result;
        }

        /// <summary>
        /// 批量添加（逐条执行）
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        [Light.Aop.CacheMethod(UpdateCache = true)]
        public virtual OperateResult Create(List<T> models)
        {
            OperateResult result = Validate(models.ToArray());

            if (result.IsSucced)
            {
                result = Excute(Create, models);
            }
            return result;
        }

        [Light.Aop.CacheMethod(UpdateCache = true)]
        public virtual OperateResult Delete(string id)
        {
            OperateResult result = new OperateResult() { IsSucced = false };
            T obj = Get(id);
            return Delete(obj);
        }

        [Light.Aop.CacheMethod(UpdateCache = true)]
        public virtual OperateResult Delete(List<string> ids)
        {
            OperateResult result = new OperateResult();

            if (ids == null && ids.Count == 0)
            {
                result.IsSucced = false;
                result.Message = "请选择要删除的记录";
                return result;
            }

            int countSucced = 0;
            int countFailed = 0;
            StringBuilder builder = new StringBuilder();

            foreach (var id in ids)
            {
                result = Delete(id);

                if (result.IsSucced)
                {
                    countSucced++;
                }
                else
                {
                    countFailed++;
                    builder.Append(result.Message + ";");
                }
            }

            if (countFailed == ids.Count)
            {
                result.IsSucced = false;
                result.Message = builder.ToString();
            }
            else
            {
                result.IsSucced = true;
                result.Message = "成功删除" + countSucced + "条记录";

                if (countFailed > 0)
                {
                    ServerApplication.Logger.LogError(result.Message);
                }
            }
            return result;
        }

        /// <summary>
        /// 更新（默认不更新多对多关联表）
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [Light.Aop.CacheMethod(UpdateCache = true)]
        public virtual OperateResult Update(T obj)
        {
            return this.Update(obj, null);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="column">需要更新的项</param>
        /// <returns></returns>
        [Light.Aop.CacheMethod(UpdateCache = true)]
        public virtual OperateResult Update(T obj, UpdateColumn column)
        {
            OperateResult result = new OperateResult();

            result = ValidateData(obj);
            if (result.IsSucced)
            {
                SearchArgs args = GetExistArgs(obj);
                int countExits = 0;
                if (args != null)
                {
                    args.Add(SearchLogic.And, "ID", SearchOperator.Not, obj.ID);
                    countExits = EntityMediator<T>.Count(args);
                }
                if (countExits > 0)
                {
                    result.IsSucced = false;
                    result.Message = GetExistMessage(obj);
                }
                else
                {
                    if (column != null)
                    {
                        #region 指定了更新哪些列的情况

                        BeforeSave(obj);

                        if (obj.IsValidated == false)
                        {
                            result.IsSucced = false;
                            result.Message = obj.GetErrorMessage();

                            return result;
                        }

                        result = EntityMediator<T>.Update(obj, column);

                        if (result.IsSucced)
                        {
                            bool traceable = ReflectionHelper.HasAttribute<TraceableAttribute>(typeof(T));
                            if (traceable)
                            {
                                string name = ReflectionHelper.GetAttributeValue<TraceableAttribute>(typeof(T), "Name");
                                if (String.IsNullOrEmpty(name))
                                {
                                    name = ReflectionHelper.GetDisplayName(typeof(T));
                                }
                                string message = string.Format("{0}【{1}】{2} 操作人：{3}", name, obj.ToString(), "修改成功", ServerApplication.User != null ? ServerApplication.User.Name : "系统");
                                ServerApplication.Logger.LogOperation(message);
                            }
                            AfterSaved(obj);

                        }

                        #endregion
                    }
                    else
                    {
                        result = Excute(EntityMediator<T>.Update, obj, OperateType.Update);
                    }
                }
            }

            return result;
        }

        [Light.Aop.CacheMethod(UpdateCache = true)]
        public virtual OperateResult Update(List<T> objs, UpdateColumn column)
        {
            return EntityMediator<T>.Update(objs, column);
        }

        [Light.Aop.CacheMethod(UpdateCache = true)]
        public virtual OperateResult Update(List<T> objs)
        {
            return Excute(Update, objs);
        }

        [Light.Aop.CacheMethod(UpdateCache = true)]
        public virtual OperateResult Save(T obj)
        {
            if (obj.IsNew)
            {
                return Create(obj);
            }
            else
            {
                return Update(obj);
            }
        }

        [Light.Aop.CacheMethod(UpdateCache = true)]
        public virtual OperateResult Save(List<T> objs)
        {
            return Excute(Save, objs);
        }

        /// <summary>
        /// 验证数据（是否符合业务逻辑）
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public virtual OperateResult ValidateData(T obj)
        {
            return new OperateResult() { IsSucced = true };
        }

        [Light.Aop.CacheMethod(UpdateCache = true)]
        public virtual OperateResult Delete(T obj)
        {
            return Excute(EntityMediator<T>.Delete, obj, OperateType.Delete);
        }

        [Light.Aop.CacheMethod(UpdateCache = true)]
        public virtual OperateResult Delete(List<T> models)
        {
            return Excute(Delete, models);
        }

        /// <summary>
        /// 获取第一条记录
        /// </summary>
        /// <returns></returns>
        public virtual T Get()
        {
            return EntityMediator<T>.Get();
        }

        /// <summary>
        /// 根据ID查找对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual T Get(string id)
        {
            return this.Get(id, null);
        }

        /// <summary>
        /// 根据ID查找对象
        /// </summary>
        /// <param name="id"></param>
        /// <param name="resultColumn">需要查询的属性名称列表</param>
        /// <returns></returns>
        public virtual T Get(string id, ResultColumn resultColumn)
        {
            return EntityMediator<T>.Get(id, resultColumn);
        }

        /// <summary>
        /// 查询符合条件的单个对象
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public virtual T Get(SearchArgs args)
        {
            return this.Get(args, null);
        }

        /// <summary>
        /// 查询符合条件的单个对象
        /// </summary>
        /// <param name="args"></param>
        /// <param name="resultColumn">需要查询的属性名称列表</param>
        /// <returns></returns>
        public virtual T Get(SearchArgs args, ResultColumn resultColumn)
        {
            return EntityMediator<T>.Get(args, resultColumn);
        }

        /// <summary>
        /// 查询所有记录
        /// </summary>
        /// <returns></returns>
        public virtual List<T> GetAll(int resultCount)
        {
            return this.GetAll(new ResultColumn(), resultCount);
        }
        public virtual List<T> GetAll()
        {
            return this.GetAll(new ResultColumn(), 0);
        }

        /// <summary>
        /// 查询所有记录
        /// </summary>
        /// <param name="ignorProperties">不需要查询的属性名称列表</param>
        /// <returns></returns>
        public virtual List<T> GetAll(ResultColumn resultColumn, int resultCount)
        {
            return EntityMediator<T>.GetAll(null, null, resultColumn, resultCount);
        }
        public virtual List<T> GetAll(ResultColumn resultColumn)
        {
            return EntityMediator<T>.GetAll(null, null, resultColumn, 0);
        }

        /// <summary>
        /// 查询所有记录
        /// </summary>
        /// <param name="args">查询参数</param>
        /// <returns></returns>
        public virtual List<T> GetAll(SearchArgs args, int resultCount)
        {
            return this.GetAll(args, new ResultColumn(), resultCount);
        }
        public virtual List<T> GetAll(SearchArgs args)
        {
            return this.GetAll(args, new ResultColumn(), 0);
        }


        /// <summary>
        /// 查询所有记录
        /// </summary>
        /// <param name="args">查询参数</param>
        /// <param name="resultColumn">需要查询的属性名称列表</param>
        /// <returns></returns>
        public virtual List<T> GetAll(SearchArgs args, ResultColumn resultColumn, int resultCount)
        {
            return EntityMediator<T>.GetAll(args, null, resultColumn, resultCount);
        }
        public virtual List<T> GetAll(SearchArgs args, ResultColumn resultColumn)
        {
            return EntityMediator<T>.GetAll(args, null, resultColumn, 0);
        }

        /// <summary>
        /// 查询所有记录
        /// </summary>
        /// <param name="args">查询参数</param>
        /// <param name="order">排序参数</param>
        public virtual List<T> GetAll(SearchArgs args, ResultOrder order, int resultCount)
        {
            return this.GetAll(args, order, null, resultCount);
        }
        public virtual List<T> GetAll(SearchArgs args, ResultOrder order)
        {
            return this.GetAll(args, order, null, 0);
        }

        /// <summary>
        /// 查询所有记录
        /// </summary>
        /// <param name="args">查询参数</param>
        /// <param name="order">排序参数</param>
        /// <param name="resultColumn">需要查询的属性名称列表</param>
        public virtual List<T> GetAll(SearchArgs args, ResultOrder order, ResultColumn resultColumn, int resultCount)
        {
            return EntityMediator<T>.GetAll(args, order, resultColumn, resultCount);
        }
        public virtual List<T> GetAll(SearchArgs args, ResultOrder order, ResultColumn resultColumn)
        {
            return EntityMediator<T>.GetAll(args, order, resultColumn, 0);
        }


        /// <summary>
        /// 查询所有记录
        /// </summary>
        /// <param name="args">查询参数</param>
        /// <param name="order">排序参数</param>
        /// <param name="resultColumn">需要查询的属性名称列表</param>
        //public virtual List<T> GetAll(SearchArgs args, ResultOrder order, ResultColumn resultColumn, int reusltCount)
        //{
        //}

        /// <summary>
        /// 查询表或视图的所有记录
        /// </summary>
        /// <param name="tableOrViewName">表或视图名称</param>
        /// <param name="searchArgs">查询参数</param>
        /// <param name="resultOrder">排序参数</param>
        /// <returns></returns>
        public virtual DataTable GetAll(string tableOrViewName, SearchArgs searchArgs, ResultOrder resultOrder)
        {
            return DataTableMediator.GetAll(tableOrViewName, searchArgs, resultOrder, new ResultColumn());
        }

        /// <summary>
        /// 查询表或视图的所有记录
        /// </summary>
        /// <typeparam name="T1">要转换的目标实体类型</typeparam>
        /// <param name="tableOrViewName">表或视图名称</param>
        /// <param name="searchArgs">查询参数</param>
        /// <param name="resultOrder">排序参数</param>
        /// <param name="customerPPs">类自定义类属性的属性名称，如：Creater.Name</param>
        /// <returns></returns>
        public virtual List<T1> GetAll<T1>(string tableOrViewName, SearchArgs searchArgs, ResultOrder resultOrder, params string[] customerPPs) where T1 : class, new()
        {
            DataTable dt = DataTableMediator.GetAll(tableOrViewName, searchArgs, resultOrder, new ResultColumn());
            return DataTableHelper.ConvertTo<T1>(dt, customerPPs);
        }

        /// <summary>
        /// 查询表或视图的所有记录
        /// </summary>
        /// <param name="tableOrViewName">表或视图名称</param>
        /// <param name="searchArgs">查询参数</param>
        /// <param name="resultOrder">排序参数</param>
        /// <param name="column">查询结果列</param>
        /// <returns></returns>
        public virtual DataTable GetAll(string tableOrViewName, SearchArgs searchArgs, ResultOrder resultOrder, ResultColumn column)
        {
            return DataTableMediator.GetAll(tableOrViewName, searchArgs, resultOrder, column);
        }

        /// <summary>
        /// 查询表或视图的所有记录
        /// </summary>
        /// <typeparam name="T1">要转换的目标实体类型</typeparam>
        /// <param name="tableOrViewName">表或视图名称</param>
        /// <param name="searchArgs">查询参数</param>
        /// <param name="resultOrder">排序参数</param>
        /// <param name="column">查询结果列</param>
        /// <param name="customerPPs">类自定义类属性的属性名称，如：Creater.Name</param>
        /// <returns></returns>
        public virtual List<T1> GetAll<T1>(string tableOrViewName, SearchArgs searchArgs, ResultOrder resultOrder, ResultColumn column, params string[] customerPPs) where T1 : class, new()
        {
            DataTable dt = DataTableMediator.GetAll(tableOrViewName, searchArgs, resultOrder, column);
            return DataTableHelper.ConvertTo<T1>(dt, customerPPs);
        }

        /// <summary>
        /// 分页查询对象列表
        /// </summary>
        /// <param name="searchArgs">查询参数</param>
        /// <param name="pageArgs">分页参数</param>
        /// <param name="resultOrder">排序参数</param>
        /// <param name="ignorProperties">不需要查询的属性名称列表</param>
        /// <returns></returns>
        public virtual List<T> Search(SearchArgs searchArgs, PageArgs pageArgs, ResultOrder resultOrder)
        {
            return this.Search(searchArgs, pageArgs, resultOrder, null);
        }

        /// <summary>
        /// 分页查询对象列表
        /// </summary>
        /// <param name="searchArgs">查询参数</param>
        /// <param name="pageArgs">分页参数</param>
        /// <param name="resultOrder">排序参数</param>
        /// <param name="resultColumn">不需要查询的属性名称列表</param>
        /// <returns></returns>
        public virtual List<T> Search(SearchArgs searchArgs, PageArgs pageArgs, ResultOrder resultOrder, ResultColumn resultColumn)
        {
            return EntityMediator<T>.Search(searchArgs, pageArgs, resultOrder, resultColumn);
        }

        /// <summary>
        /// 分页查询表或视图
        /// </summary>
        /// <param name="tableOrViewName">表或视图名称</param>
        /// <param name="searchArgs">查询参数</param>
        /// <param name="pageArgs">分页参数</param>
        /// <param name="resultOrder">排序参数</param>
        /// <returns></returns>
        public virtual DataTable Search(string tableOrViewName, SearchArgs searchArgs, PageArgs pageArgs, ResultOrder resultOrder)
        {
            return DataTableMediator.Search(tableOrViewName, searchArgs, pageArgs, resultOrder, new ResultColumn());
        }

        /// <summary>
        /// 分页查询表或视图
        /// </summary>
        /// <typeparam name="T1">要转换的目标实体类型</typeparam>
        /// <param name="tableOrViewName">表或视图名称</param>
        /// <param name="searchArgs">查询参数</param>
        /// <param name="pageArgs">分页参数</param>
        /// <param name="resultOrder">排序参数</param>
        /// <param name="customerPPs">类自定义类属性的属性名称，如：Creater.Name</param>
        /// <returns>T1对象集合</returns>
        public virtual List<T1> Search<T1>(string tableOrViewName, SearchArgs searchArgs, PageArgs pageArgs, ResultOrder resultOrder, params string[] customerPPs) where T1 : class, new()
        {
            DataTable dt = DataTableMediator.Search(tableOrViewName, searchArgs, pageArgs, resultOrder, new ResultColumn());
            return DataTableHelper.ConvertTo<T1>(dt, customerPPs);
        }

        /// <summary>
        /// 分页查询表或视图
        /// </summary>
        /// <param name="tableOrViewName">表或视图名称</param>
        /// <param name="searchArgs">查询参数</param>
        /// <param name="pageArgs">分页参数</param>
        /// <param name="resultOrder">排序参数</param>
        /// <param name="resultColumn">查询结果列</param>
        /// <returns></returns>
        public virtual DataTable Search(string tableOrViewName, SearchArgs searchArgs, PageArgs pageArgs, ResultOrder resultOrder, ResultColumn resultColumn)
        {
            return DataTableMediator.Search(tableOrViewName, searchArgs, pageArgs, resultOrder, resultColumn);
        }

        /// <summary>
        /// 分页查询表或视图
        /// </summary>
        /// <typeparam name="T1">要转换的目标实体类型</typeparam>
        /// <param name="tableOrViewName">表或视图名称</param>
        /// <param name="searchArgs">查询参数</param>
        /// <param name="pageArgs">分页参数</param>
        /// <param name="resultOrder">排序参数</param>
        /// <param name="resultColumn">查询结果列</param>
        /// <param name="customerPPs">类自定义类属性的属性名称，如：Creater.Name</param>
        /// <returns>T1对象集合</returns>
        public virtual List<T1> Search<T1>(string tableOrViewName, SearchArgs searchArgs, PageArgs pageArgs, ResultOrder resultOrder, ResultColumn resultColumn, params string[] customerPPs) where T1 : class, new()
        {
            DataTable dt = DataTableMediator.Search(tableOrViewName, searchArgs, pageArgs, resultOrder, resultColumn);
            return DataTableHelper.ConvertTo<T1>(dt, customerPPs);
        }
        /// <summary>
        /// 执行增，删，改操作
        /// </summary>
        /// <param name="method">方法名</param>
        /// <param name="obj">操作对象</param>
        /// <param name="type">操作类型</param>
        /// <returns></returns>
        protected OperateResult Excute(OperateDelegate<T> method, T obj, OperateType type)
        {
            if (type == OperateType.Create || type == OperateType.Update)
            {
                BeforeSave(obj);
            }

            OperateResult result = new OperateResult();
            try
            {
                if (obj.IsValidated == false)
                {
                    result.IsSucced = false;
                    result.Message = obj.GetErrorMessage();

                    return result;
                }
                switch (type)
                {
                    case OperateType.Create: result.Message = "添加失败！"; break;
                    case OperateType.Update: result.Message = "更新失败！"; break;
                    case OperateType.Delete: result.Message = "删除失败！"; break;
                    default: break;
                }
                try
                {
                    method(obj);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                result.IsSucced = true;
                string optStr = string.Empty;

                switch (type)
                {
                    case OperateType.Create: result.Message = "添加成功！"; break;
                    case OperateType.Update: result.Message = "更新成功！"; break;
                    case OperateType.Delete: result.Message = "删除成功！"; break;
                    default: break;
                }

                bool traceable = ReflectionHelper.HasAttribute<TraceableAttribute>(typeof(T));
                if (traceable)
                {
                    string name = ReflectionHelper.GetAttributeValue<TraceableAttribute>(typeof(T), "Name");
                    if (String.IsNullOrEmpty(name))
                    {
                        name = ReflectionHelper.GetDisplayName(typeof(T));
                    }
                    string message = string.Format("{0}【{1}】{2} 操作人：{3}", name, obj.ToString(), result.Message, ServerApplication.User != null ? ServerApplication.User.Name : "系统");
                    ServerApplication.Logger.LogOperation(message);
                }
            }
            catch (Exception ex)
            {
                result.IsSucced = false;

                if (ex.InnerException != null && ex.InnerException.InnerException != null)
                {
                    result.Message = ex.InnerException.InnerException.Message;
                    if (result.Message.ToUpper().Contains("FOREIGN KEY"))
                    {
                        result.Message = " 数据正在使用中,请先删除其他相关信息！";
                    }
                }
                else if (ex.InnerException != null)
                {
                    result.Message += " 错误详细：" + ex.InnerException.Message;
                }
                else
                {
                    result.Message += " 错误详细：" + ex.Message;
                }

                ServerApplication.Logger.LogError(result.Message);
            }
            if (result.IsSucced && (type == OperateType.Create || type == OperateType.Update))
            {
                AfterSaved(obj);
            }

            return result;
        }

        /// <summary>
        /// 将批量调用method方法返回的结果，汇总到一个返回值中
        /// 有一个成功，则成功；
        /// </summary>
        /// <param name="method">带一个类型为 T 的参数，且 返回值为OperateResult 的方法</param>
        /// <param name="objs"></param>
        /// <returns></returns>
        protected OperateResult Excute(OperateDelegate<T> method, List<T> objs)
        {
            OperateResult result = new OperateResult();

            int countSucced = 0;
            StringBuilder builderError = new StringBuilder();

            foreach (var model in objs)
            {
                result = method(model);
                if (result.IsSucced)
                {
                    countSucced++;
                }
                else
                {
                    builderError.Append(result.Message + ";");
                }
            }
            if (countSucced > 0)
            {
                result.IsSucced = true;
                result.Message = "操作成功";
            }
            else
            {
                result.IsSucced = false;
                result.Message = builderError.ToString();
            }

            return result;
        }

        /// <summary>
        /// 保存（新增、修改）前执行
        /// </summary>
        /// <param name="obj"></param>
        protected virtual void BeforeSave(T obj) { }

        /// <summary>
        /// 保存（新增、修改）成功后执行
        /// </summary>
        /// <param name="obj"></param>
        protected virtual void AfterSaved(T obj) { }

        #endregion


        #region 批量导入

        /// <summary>
        /// 批量导入时分批次保存每批次的数量
        /// </summary>
        protected int SizePerBatch = 50;

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public virtual OperateResult Import(DataSet ds)
        {
            OperateResult result = new OperateResult();
            if (ds == null || ds.Tables.Count == 0)
            {
                result.IsSucced = false;
                result.Message = "导入的数据为空！";
            }
            else
            {
                List<T> models = new List<T>();
                foreach (DataTable dt in ds.Tables)
                {
                    models.AddRange(ImportHelper.ConvertTo<T>(dt, GetImportColumns()));
                }

                if (models != null && models.Count > 0)
                {
                    result = Create(models);
                }
                else
                {
                    result.IsSucced = false;
                    result.Message = "导入的数据为空！";
                }
            }
            return result;
        }

        /// <summary>
        /// 获取自定义列名
        /// </summary>
        /// <returns></returns>
        public virtual Dictionary<string, string> GetCustomColumns()
        {
            return null;
        }

        /// <summary>
        /// 导入时，获取需要重命名的列字典《默认列名，实际列名》
        /// </summary>
        /// <returns></returns>
        protected virtual Dictionary<string, string> GetImportColumns()
        {

            Dictionary<string, string> customNames = GetCustomColumns();

            if (customNames != null && customNames.Count > 0)
            {

                Dictionary<string, string> dicMapping = new Dictionary<string, string>();

                Dictionary<string, string> importFields = ReflectionHelper.GetImportFields<T>(false);

                foreach (var pName in customNames.Keys)
                {
                    if (importFields.Keys.Contains(pName))
                    {
                        string oldColumnName = importFields[pName];
                        string newColumnName = customNames[pName];

                        if (dicMapping.Keys.Contains(oldColumnName))
                            dicMapping[oldColumnName] = newColumnName;
                        else
                            dicMapping.Add(oldColumnName, newColumnName);

                    }
                }

                return dicMapping;
            }
            return customNames;
        }

        /// <summary>
        /// 获取信息已存在时的提示信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        protected virtual string GetExistMessage(T model)
        {
            return model.ToString() + " 信息已存在";
        }

        /// <summary>
        /// 获取判断信息是否存在的条件
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        protected virtual SearchArgs GetExistArgs(T obj)
        {
            return null;
        }

        #endregion


        /// <summary>
        /// 从当前应用程序域中获取值
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        protected void SetValue(string name, object value)
        {
            System.Threading.Thread.GetDomain().SetData(name, value);
        }

        /// <summary>
        /// 在当前线程应用程序域中设置值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <returns></returns>
        protected T GetValue<T>(string name)
        {
            T value = default(T);

            object obj = System.Threading.Thread.GetDomain().GetData(name);
            if (obj != null)
                value = (T)obj;

            return value;
        }

        /// <summary>
        /// 设置默认值
        /// </summary>
        /// <typeparam name="TD"></typeparam>
        /// <param name="obj"></param>
        protected virtual void SetDefault<TD>(TD obj) where TD : Entity, IDefaultable, new()
        {
            //if (obj.IsDefault)
            //{
            //    ICriterion criterion = Expression.Eq("IsDefault", true);
            //    if (!obj.IsNew)
            //    {
            //        criterion = Expression.And(criterion, Expression.Not(Expression.Eq("ID", obj.ID)));
            //    }

            //    ICriterion criterionDefault = GetDefaultCriterion(obj);
            //    if (criterionDefault != null)
            //    {
            //        criterion = Expression.And(criterion, criterionDefault);
            //    }

            //    List<TD> models = EntityMediator<TD>.FindAll(criterion);
            //    foreach (var model in models)
            //    {
            //        if (model.ID != obj.ID)
            //        {
            //            model.IsDefault = false;
            //            EntityMediator<TD>.Update(model);
            //        }
            //    }
            //}
        }

        #region 私有方法

        private OperateResult Validate(params T[] models)
        {
            OperateResult result = new OperateResult();

            if (models == null || models.Length == 0)
            {
                result.IsSucced = false;
                result.Message = "导入的记录为空！";
            }
            else
            {
                StringBuilder errorBuilder = new StringBuilder();
                int length = models.Length;

                for (int i = 0; i < length; i++)
                {
                    T model = models[i];
                    if (!model.IsValidated)
                    {
                        errorBuilder.Append("第" + (i + 1).ToString() + "行记录：" + model.GetErrorMessage() + " ");
                    }
                }
                result.IsSucced = errorBuilder.Length == 0;
                result.Message = errorBuilder.ToString();
            }
            return result;
        }

        #endregion
    }
}
